import React, { useState ,useEffect} from 'react'
import { Button, Checkbox, Form, Input,Col, Row } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Link, useNavigate } from "react-router-dom"
import "./index.less"
import { LoginApi } from "request/api"
import { message } from 'antd';

const logo = require("assets/images/logo.png")

interface IRegisterLogin {
  username: string ;
  password: string ;
  password1?: string ;
  remember:boolean;
}

const regPassword = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,18}$/ //密码邮箱正则
const regUsername = /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{4,16}$/ // 账户正则


export default function Login() {
  let navigate = useNavigate()
  
  const formRef:any = React.createRef()

  useEffect(()=>{
    if(localStorage.getItem('remember') == '1'){

      formRef.current.setFieldsValue({
        username :localStorage.getItem('username'),
        password :localStorage.getItem('password'),
        remember:true
      })
    }
  },[])

  const onFinish = (values: IRegisterLogin) => {
    console.log(values)
    interface IRes {
      errCode?: number,
      message?: string,
      data?: any;
    }

    LoginApi(values).then((res: IRes) => {
      if (res.errCode === 0) {

        message.success(res.message, 1.5)

        if(values.remember){
          localStorage.setItem("username",values.username)
          localStorage.setItem("password",values.password)
          localStorage.setItem("remember",values.remember?'1':'0')
        }else{
          localStorage.setItem("remember",'0')
        }

        localStorage.setItem("cms-token",res.data['cms-token'])
        localStorage.setItem("avatar",res.data.avatar)
        localStorage.setItem("player",res.data.player)
        localStorage.setItem("editable",res.data.editable)
        setTimeout(() => {
          navigate('/')
        }, 1500)
      }else{
        message.error(res.message, 1.5)
        return
      }
      
    })
  };

const onFinishFailed = (errorInfo: any) => {
};

return (
  <div className='login_box'>
    <img src={logo} className="logo" alt="" />
    <Form
      name="basic"
      ref={formRef} 
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
      size='large'
    >
      <Form.Item
        name="username"
        rules={[{ 
          required: true, 
          message: '请输入用户名!' 
        }, ({ getFieldValue }) => ({
          validator(_, value) {
            console.log(regUsername.test(value))
            if (!value || regUsername.test(value) || value == 'admin') {
              return Promise.resolve();
            }
            return Promise.reject(new Error('请输入由字母、数字组成4-16位账户'));
          },
        }),
        ]}
      >
        <Input  prefix={<UserOutlined className="site-form-item-icon" />} placeholder='请输入用户名' />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[{ 
            required: true, 
            message: '请输入密码!' 
          }, ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || regPassword.test(value)|| value=='123456') {
                return Promise.resolve();
              }
              return Promise.reject(new Error('请输入由字母、数字、特殊符号组成8-18位密码'));
            },
          }),
        ]}
      >
        <Input.Password  prefix={<LockOutlined className="site-form-item-icon" />} placeholder='请输入密码' />
      </Form.Item>

      <Row>
        <Col span={8}>
          <Form.Item name="remember" valuePropName="checked" >
            <Checkbox>记住我</Checkbox>
          </Form.Item>
        </Col>

        <Col span={6}></Col>
        <Col span={5}></Col>

        <Col span={5}>
          <Form.Item >
            <Link  to="/forgetPassword" >忘记密码？</Link>
          </Form.Item>
        </Col>
      </Row>

      

      <Form.Item>
        <Button type="primary" block htmlType="submit" size='large'>
          登录
        </Button>
      </Form.Item>

      <Form.Item >
        <Link to="/register" >还没账号？立即注册</Link>
      </Form.Item>
    </Form>
  </div>
);
}
